﻿using Leo.Common.MQ;
using Microsoft.Extensions.Hosting;

namespace Leo.Common.RabbitMQ
{
    //[NullableContext(1)]
    //[Nullable(0)]
    public class RabbitConsumerHostedService : BackgroundService
    {
        private readonly RabbitBuilder builder;

        private readonly IServiceProvider serviceProvider;

        public RabbitConsumerHostedService(RabbitBuilder builder, IServiceProvider serviceProvider)
        {
            this.builder = builder;
            this.serviceProvider = serviceProvider;
        }
         
        protected override Task ExecuteAsync(CancellationToken stoppingToken)
        {
            foreach (RabbitQueueInfo rabbitQueueInfo in from x in this.builder.Queues
                                                        where !x.preventDefaultConsumer && x.handlerTypes.Any<HandlerDescriptor>()
                                                        select x)
            {
                List<IMessageHandler> handlerInstances = rabbitQueueInfo.GetHandlerInstances(this.serviceProvider);
                RabbitConsumer rabbitConsumer = new RabbitConsumer(this.builder.Connection, rabbitQueueInfo, handlerInstances.ToArray());
                this.builder.Consumers.Add(rabbitConsumer);
                rabbitConsumer.Start();
            }
            return Task.CompletedTask;
        }
         
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            this.builder.Connection.Dispose();
            return base.StopAsync(cancellationToken);
        }

    }
}
